<?php
declare (strict_types=1);

namespace app;

use app\exception\BusinessException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use think\db\exception\PDOException;
class ExceptionHandle extends Handle
{
    // 不需要记录日志的异常类列表
    protected $ignoreReport = [
        BusinessException::class,
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
    ];

    public function report(Throwable $exception): void
    {
        // 记录异常到日志系统
        if (!$this->isIgnoreReport($exception)) {
            $this->logService($exception);
        }
    }

    public function render($request, Throwable $e): Response
    {
        if ($e instanceof \think\exception\TokenException) {
            return json([
                'code' => 401,
                'msg'  => $e->getMessage()
            ], 401);
        } 
        if ( $e instanceof ModelNotFoundException) {
            return json([
                'code' => 401,
                'msg'  => "数据不存在"
            ], 404);
        }
        // 自定义异常处理
        if ($e instanceof BusinessEBuxception) {
            return $this->renderBusinessException($e);
        }

        if ($e instanceof ValidateException) {
            return $this->renderValidateException($e);
        }

        if ($e instanceof HttpException) {
            return $this->renderHttpException($e);
        }

        if($e instanceof PDOException){
            return $this->renderPDOException($e);
        }
        // 其他异常处理
        return parent::render($request, $e);
    }

    /**
     * 业务异常处理
     */
    protected function renderBusinessException(BusinessException $e): Response
    {
        return json([
            'code'  => $e->getCode(),
            'msg'   => $e->getMessage(),
            'data'  => null,
            'error' => $this->app->isDebug() ? [
                'file'  => $e->getFile(),
                'line'  => $e->getLine()
            ] : null
        ], $e->getStatusCode());
    }

    /**
     * 验证异常处理
     */
    protected function renderValidateException(ValidateException $e): Response
    {
        return json([
            'code'  => 40001,
            'msg'   => '参数验证失败',
            'data'  => null,
            'errors' => $e->getError()
        ], 422);
    }

    /**
     * HTTP异常处理
     */
    protected function renderHttpException(HttpException $e): Response
    {
        return json([
            'code' => $e->getStatusCode(),
            'msg'  => $e->getMessage(),
            'data' => null
        ], $e->getStatusCode());
    }

    protected function renderPDOException(PDOException $e): Response    {
        return json([
            'code' => 500,
            'msg'  => '数据库异常'.$e->getMessage(),
            'data' => null
        ], 500);
    }

    /**
     * 记录异常日志
     */
    protected function logService(Throwable $e): void
    {
        $logData = [
            'request' => [
                'method' => request()->method(),
                'url'    => request()->url(),
                'ip'     => request()->ip()
            ],
            'exception' => [
                'message' => $e->getMessage(),
                'code'    => $e->getCode(),
                'file'    => $e->getFile(),
                'line'    => $e->getLine()
            ]
        ];

        \think\facade\Log::error(json_encode($logData, JSON_UNESCAPED_SLASHES));
    }
}
